import React, { PureComponent } from 'react';
import { Modal, Input, Button, message, Radio,Select,InputNumber, Icon, } from 'antd';
import styles from '@/common/PateoTable/TableList.less';
import * as G from '@/utils/common';
import { connect } from 'dva';
import { transferOption } from '@/support/utils';
import { Form } from '@ant-design/compatible';

const FormItem = Form.Item;
const { Group: RadioGroup } = Radio;
let id = 3;

@connect((state) => ({
  fieldManage: state.fieldManage,
}))
@Form.create()
export default class AddModal extends PureComponent {
  state = {
    buttonLoading: false,
    optionVisible: false,
    numVibible: false,
    selectSuffixText: "",// 自定义的选择框后缀图标
  };

  componentDidMount() {
  }

  ok = (e) => {
    e.preventDefault();
    const { dispatch,form } = this.props;
    const{optionVisible,numVibible}=this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setLoading(true);
      const params={};
      params.groupId =fieldsValue.groupId;
      params.name = fieldsValue.name;
      params.type = Number(fieldsValue.type);
      if(numVibible === true && optionVisible === false){
        params.digit = fieldsValue.digit
      };
      if(optionVisible === true && numVibible === false){
        params.selectType = fieldsValue.selectType
      };
      if(optionVisible === true && numVibible === false){
        const arr =[];
        (fieldsValue.optionList).map(item =>{
           if(!!item){
            arr.push(item);
           }
         })
         params.optionList = arr;
      }
      dispatch({
        type: 'fieldManage/postObjWithRes',
        payload: { url: '/mscreditbusiness/credit/merchant/field/save',
          ...params
        },
        callback: response=>{
          if (response.statusCode === '0') {
            message.success('添加成功');
            this.close();
          } else {
            this.setLoading(false);
            message.error(response.statusMessage);
          }
        }
      })
    });
  };
  setLoading = (flag) => {
    this.setState({
      buttonLoading: flag,
    });
  }
  close = () => {
    const { closeModal, form} = this.props;
    form.resetFields();
    this.setState({
      buttonLoading: false,
      optionVisible: false,
      numVibible: false,
      selectSuffixText: ""
    });
    closeModal();
  }

  handleTypeChange = (value) => {
    const {form } = this.props;
    this.setState({
      selectSuffixText: "",
    });
    if(value == 2) {
      this.setState({
        optionVisible: true,
        numVibible: false,
      })
    } else if (value == 3) {
      this.setState({
        optionVisible: false,
        numVibible: true,
      })
      setTimeout(() => {
        form.setFieldsValue(
          {
            digit: 2,
          },
          () => {
            this.setState({
              selectSuffixText: `1024.${[...Array(form.getFieldValue("digit"))]
                .map((i) => 0)
                .join("")}`,
            });
          }
        );
      }, 300);
    } else{
      this.setState({
        optionVisible: false,
        numVibible: false,
      })
      if(value == 4){
        this.setState({
          selectSuffixText: "2022-01-01",
        });
      }else if(value == 5){
        this.setState({
          selectSuffixText: "23:59:59",
        });
      }else if(value == 6){
        this.setState({
          selectSuffixText: "2022-01-01 23:59:59",
        });
      }
    }
  }
  // 删除选项
  remove = k => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }
    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };
 //新增选项
  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    const nextKeys = keys.concat(id++);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
  };

  renderSimpleForm() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { modalVisible,fieldNum,groupList } = this.props;
    const { buttonLoading, optionVisible,numVibible,selectSuffixText } = this.state;
    const typeList = [{label:'文本',value: 1},{label:'下拉列表',value: 2},{label:'数字',value: 3},
    {label:'日期',value: 4},{label:'时间',value: 5},{label:'日期时间',value: 6},{label:'URL连接',value: 7}]
    const footer = (
      <div>
        <Button onClick={this.close}>取消</Button>
        <Button loading={buttonLoading} onClick={this.ok} type="primary">保存</Button>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };
    getFieldDecorator('keys', { initialValue: [0,1,2] });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <Form.Item
        {...formItemLayoutWithOutLabel}
        label={''}
        required={false}
        key={k}
      >
        {getFieldDecorator(`optionList[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [
            {
              required: optionVisible,
              whitespace: true,
              message: "请输入选项",
            },
          ],
        })(<Input placeholder="请输入选项" style={{ width: '60%', marginRight: 8 }} />)}
          <Button
            type="primary"
            onClick={() => this.remove(k)}
          >删除
          </Button>
      </Form.Item>
    ));
    return (
      <Modal
        footer={footer}
        title={`新增字段(${fieldNum})/100`}
        okText="保存"
        visible={modalVisible}
        onCancel={this.close}
        //width="60%"
      >
        <Form
          style={{ marginTop: 12 }}
        >
        <FormItem
        {...formItemLayout}
        label="字段分组"
      >
        {getFieldDecorator('groupId', {
          rules: [
            { required: true, message: '请选择字段分组' },
          ],
        })(
          <Select
          placeholder='请选择'
          optionFilterProp="children"
          allowClear={true}
          showSearch
          getPopupContainer={triggerNode => triggerNode.parentNode}
        >
          {transferOption(groupList, ['uuid', 'name'])}
        </Select>
        )}
      </FormItem>
      <FormItem
            {...formItemLayout}
            label="字段名称"
          >
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请输入字段名称' },
              ],
            })(
              <Input maxLength={32} placeholder="请输入"/>
            )}
      </FormItem>
      <FormItem
        {...formItemLayout}
        label="字段类型"
      >
        {getFieldDecorator('type', {
          rules: [
            { required: true, message: '请选择字段类型' },
          ],
        })(
          <Select
          placeholder='请选择'
          optionFilterProp="children"
          allowClear={true}
          showSearch
          getPopupContainer={triggerNode => triggerNode.parentNode}
          onChange={this.handleTypeChange}
          suffixIcon={
            <>
              <span
                style={{
                  color: "rgba(0,0,0,.25)",
                  lineHeight: "12px",
                  height: "12px",
                  display: "inline-block",
                  marginRight: "5px",
                }}
              >
                {selectSuffixText}
              </span>
              <Icon type="down" />
            </>
          }
        >
          {G.transferOption(typeList, ['value', 'label'])}
        </Select>
        )}
      </FormItem>
      { this.state.numVibible &&
      <FormItem
        label="小数位数"
        wrapperCol={{
          span: 6,
        }}
        labelCol={{
          offset: 3,
          span: 6,
        }}
      >
        {getFieldDecorator('digit', {
          rules: [
            { required: numVibible, message: '请选择小数位数' },
          ],
        })(
          <InputNumber 
          min={0}
          max={4}
          onChange={(e) => {
            this.setState({
              selectSuffixText: !!e
                ? `1024.${[...Array(e)].map((i) => 0).join("")}`
                : "1024",
            });
          }}
          />
        )}
      </FormItem>
       }
    {this.state.optionVisible && 
      <FormItem
       label=""
         wrapperCol={{
          offset: 5,
          span: 16,
        }}
        labelCol={{
          offset: 5,
          span: 16,
        }}
      >
        {getFieldDecorator('selectType', {
          rules: [
            { required: optionVisible, message: '请选择下拉列表类型' },
          ],
        })(
          <Radio.Group>
          <Radio value={0}>单选</Radio>
          <Radio value={1}>多选</Radio>
        </Radio.Group>
        )}
      </FormItem>
    }
      {this.state.optionVisible && formItems}
      {this.state.optionVisible &&
      <FormItem {...formItemLayoutWithOutLabel} > 
          <Button type="primary" onClick={this.add} style={{ width: '60%' }}>
            <Icon type="plus" />新增选项
          </Button>
      </FormItem>
     }
        </Form>
      </Modal>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return (
      <div className={styles.tableListForm}>
        {this.renderForm()}
      </div>
    );
  }
}
